<template>
  <div id="appChatPage">
    <!-- 顶部栏 -->
    <div class="header-bar">
      <div class="header-left">
        <h1 class="app-name">{{ appInfo?.appName || "网站生成器" }}</h1>
        <a-tag v-if="appInfo?.codeGenType" color="blue" class="code-gen-type-tag">
          {{ formatCodeGenType(appInfo.codeGenType) }}
        </a-tag>
      </div>
      <div class="header-right">
        <a-button type="default" @click="showAppDetail">
          <template #icon>
            <InfoCircleOutlined />
          </template>
          应用详情
        </a-button>
        <a-button
          type="primary"
          ghost
          @click="downloadCode"
          :loading="downloading"
          :disabled="!isOwner"
        >
          <template #icon>
            <DownloadOutlined />
          </template>
          下载代码
        </a-button>
        <a-button type="primary" :loading="deploying" @click="deployApp">
          <template #icon>
            <CloudUploadOutlined />
          </template>
          部署
        </a-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧对话区域 -->
      <AppChatArea
        ref="appChatAreaRef"
        v-model:messages="messages"
        v-model:is-generating="isGenerating"
        :app-id="appId"
        :is-owner="isOwner"
        :has-more-history="hasMoreHistory"
        :loading-history="loadingHistory"
        :selected-element-info="selectedElementInfo"
        :is-edit-mode="isEditMode"
        @load-more-history="loadMoreHistory"
        @clear-selected-element="clearSelectedElement"
        @toggle-edit-mode="toggleEditMode"
        @update-view="updateView"
      />
      <!-- 右侧网页展示区域 -->
      <AppPreviewArea
        v-model:preview-ready="previewReady"
        :is-owner="isOwner"
        :is-generating="isGenerating"
        :is-edit-mode="isEditMode"
        :preview-url="previewUrl"
        :visual-editor="visualEditor"
        @toggle-edit-mode="toggleEditMode"
      />
    </div>

    <!-- 应用详情弹窗 -->
    <AppDetailModal
      v-model:open="appDetailVisible"
      :app="appInfo"
      :show-actions="isOwner || isAdmin"
      @edit="editApp"
      @delete="deleteApp"
    />

    <!-- 部署成功弹窗 -->
    <DeploySuccessModal
      v-model:open="deployModalVisible"
      :deploy-url="deployUrl"
      @open-site="openDeployedSite"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue"
import { useRoute, useRouter } from "vue-router"
import { message } from "ant-design-vue"
import { useLoginUserStore } from "@/stores/loginUser"
import {
  getAppVoById,
  deployApp as deployAppApi,
  deleteApp as deleteAppApi
} from "@/api/appController"
import { listAppChatHistory } from "@/api/chatHistoryController"
import { CodeGenTypeEnum, formatCodeGenType } from "@/utils/codeGenTypes"
import request from "@/request"
import AppDetailModal from "@/components/AppDetailModal.vue"
import AppChatArea from "@/components/AppChatArea.vue"
import DeploySuccessModal from "@/components/DeploySuccessModal.vue"
import { getStaticPreviewUrl } from "@/config/env"
import { VisualEditor, type ElementInfo } from "@/utils/visualEditor"
import { CloudUploadOutlined, InfoCircleOutlined, DownloadOutlined } from "@ant-design/icons-vue"
import AppPreviewArea from "@/components/AppPreviewArea.vue"
import type { Message } from "@/types/app"

const appChatAreaRef = ref<InstanceType<typeof AppChatArea> | null>(null)

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

// 应用信息
const appInfo = ref<API.AppVO>()
const appId = ref<string>("")

// 消息相关
const messages = ref<Message[]>([])
// 是否正在生成网站
const isGenerating = ref(false)

// 对话历史相关
const loadingHistory = ref(false)
const hasMoreHistory = ref(false)
const lastCreateTime = ref<string>()
const historyLoaded = ref(false)

// 预览相关
const previewUrl = ref("")
const previewReady = ref(false)

// 部署相关
const deploying = ref(false)
const deployModalVisible = ref(false)
const deployUrl = ref("")

// 下载相关
const downloading = ref(false)

// 可视化编辑相关
const isEditMode = ref(false)
const selectedElementInfo = ref<ElementInfo | null>(null)
const visualEditor = new VisualEditor({
  onElementSelected: (elementInfo: ElementInfo) => {
    selectedElementInfo.value = elementInfo
  }
})

// 权限相关
const isOwner = computed(() => {
  return appInfo.value?.userId === loginUserStore.loginUser.id
})

const isAdmin = computed(() => {
  return loginUserStore.loginUser.userRole === "admin"
})

// 应用详情相关
const appDetailVisible = ref(false)

// 显示应用详情
const showAppDetail = () => {
  appDetailVisible.value = true
}

// 加载对话历史
const loadChatHistory = async (isLoadMore = false) => {
  if (!appId.value || loadingHistory.value) return
  loadingHistory.value = true
  try {
    const params: API.listAppChatHistoryParams = {
      appId: appId.value,
      pageSize: 10
    }
    // 如果是加载更多，传递最后一条消息的创建时间作为游标
    if (isLoadMore && lastCreateTime.value) {
      params.lastCreateTime = lastCreateTime.value
    }
    const res = await listAppChatHistory(params)
    if (res.data.code === 0 && res.data.data) {
      const chatHistories = res.data.data.records || []
      if (chatHistories.length > 0) {
        // 将对话历史转换为消息格式，并按时间正序排列（老消息在前）
        const historyMessages: Message[] = chatHistories
          .map((chat) => ({
            type: (chat.messageType === "user" ? "user" : "ai") as "user" | "ai",
            content: chat.message || "",
            createTime: chat.createTime
          }))
          .reverse() // 反转数组，让老消息在前
        if (isLoadMore) {
          // 加载更多时，将历史消息添加到开头
          messages.value.unshift(...historyMessages)
        } else {
          // 初始加载，直接设置消息列表
          messages.value = historyMessages
        }
        // 更新游标
        lastCreateTime.value = chatHistories[chatHistories.length - 1]?.createTime
        // 检查是否还有更多历史
        hasMoreHistory.value = chatHistories.length === 10
      } else {
        hasMoreHistory.value = false
      }
      historyLoaded.value = true
    }
  } catch (error) {
    console.error("加载对话历史失败：", error)
    message.error("加载对话历史失败")
  } finally {
    loadingHistory.value = false
  }
}

// 加载更多历史消息
const loadMoreHistory = async () => {
  await loadChatHistory(true)
}

// 获取应用信息
const fetchAppInfo = async () => {
  const id = route.params.id as string
  if (!id) {
    message.error("应用ID不存在")
    router.push("/")
    return
  }

  appId.value = id

  try {
    const res = await getAppVoById({ id })
    if (res.data.code === 0 && res.data.data) {
      appInfo.value = res.data.data

      // 先加载对话历史
      await loadChatHistory()
      // 如果有至少2条对话记录，展示对应的网站
      if (messages.value.length >= 2) {
        updatePreview()
      }
      // 检查是否需要自动发送初始提示词
      // 只有在是自己的应用且没有对话历史时才自动发送
      if (
        appInfo.value.initPrompt &&
        isOwner.value &&
        messages.value.length === 0 &&
        historyLoaded.value
      ) {
        await appChatAreaRef.value?.sendInitialMessage(appInfo.value.initPrompt)
      }
    } else {
      message.error("获取应用信息失败")
      router.push("/")
    }
  } catch (error) {
    console.error("获取应用信息失败：", error)
    message.error("获取应用信息失败")
    router.push("/")
  }
}

// 更新预览
const updatePreview = () => {
  if (appId.value) {
    const codeGenType = appInfo.value?.codeGenType || CodeGenTypeEnum.HTML
    const newPreviewUrl = getStaticPreviewUrl(codeGenType, appId.value)
    previewUrl.value = newPreviewUrl
    previewReady.value = true
  }
}

// 更新预览
const updateView = async () => {
  await fetchAppInfo()
  updatePreview()
}

// 下载代码
const downloadCode = async () => {
  if (!appId.value) {
    message.error("应用ID不存在")
    return
  }
  downloading.value = true
  try {
    const API_BASE_URL = request.defaults.baseURL || ""
    const url = `${API_BASE_URL}/app/download/${appId.value}`
    const response = await fetch(url, {
      method: "GET",
      credentials: "include"
    })
    if (!response.ok) {
      throw new Error(`下载失败: ${response.status}`)
    }
    // 获取文件名
    const contentDisposition = response.headers.get("Content-Disposition")
    const fileName = contentDisposition?.match(/filename="(.+)"/)?.[1] || `app-${appId.value}.zip`
    // 下载文件
    const blob = await response.blob()
    const downloadUrl = URL.createObjectURL(blob)
    const link = document.createElement("a")
    link.href = downloadUrl
    link.download = fileName
    link.click()
    // 清理
    URL.revokeObjectURL(downloadUrl)
    message.success("代码下载成功")
  } catch (error) {
    console.error("下载失败：", error)
    message.error("下载失败，请重试")
  } finally {
    downloading.value = false
  }
}

// 部署应用
const deployApp = async () => {
  if (!appId.value) {
    message.error("应用ID不存在")
    return
  }

  deploying.value = true
  try {
    const res = await deployAppApi({
      appId: appId.value
    })

    if (res.data.code === 0 && res.data.data) {
      deployUrl.value = res.data.data
      deployModalVisible.value = true
      message.success("部署成功")
    } else {
      message.error("部署失败：" + res.data.message)
    }
  } catch (error) {
    console.error("部署失败：", error)
    message.error("部署失败，请重试")
  } finally {
    deploying.value = false
  }
}

// 打开部署的网站
const openDeployedSite = () => {
  if (deployUrl.value) {
    window.open(deployUrl.value, "_blank")
  }
}

// 编辑应用
const editApp = () => {
  if (appInfo.value?.id) {
    router.push(`/app/edit/${appInfo.value.id}`)
  }
}

// 删除应用
const deleteApp = async () => {
  if (!appInfo.value?.id) return

  try {
    const res = await deleteAppApi({ id: appInfo.value.id })
    if (res.data.code === 0) {
      message.success("删除成功")
      appDetailVisible.value = false
      router.push("/")
    } else {
      message.error("删除失败：" + res.data.message)
    }
  } catch (error) {
    console.error("删除失败：", error)
    message.error("删除失败")
  }
}

// 可视化编辑相关函数
const toggleEditMode = () => {
  // 检查 iframe 是否已经加载
  const iframe = document.querySelector(".preview-iframe") as HTMLIFrameElement
  if (!iframe) {
    message.warning("请等待页面加载完成")
    return
  }
  // 确保 visualEditor 已初始化
  if (!previewReady.value) {
    message.warning("请等待页面加载完成")
    return
  }
  const newEditMode = visualEditor.toggleEditMode()
  isEditMode.value = newEditMode
}

const clearSelectedElement = () => {
  selectedElementInfo.value = null
  visualEditor.clearSelection()
}

// 页面加载时获取应用信息
onMounted(() => {
  fetchAppInfo()

  // 监听 iframe 消息
  window.addEventListener("message", (event) => {
    visualEditor.handleIframeMessage(event)
  })
})

// 清理资源
onUnmounted(() => {
  // EventSource 会在组件卸载时自动清理
})
</script>

<style scoped>
#appChatPage {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background: #fdfdfd;
}

/* 顶部栏 */
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.code-gen-type-tag {
  font-size: 12px;
}

.app-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.header-right {
  display: flex;
  gap: 12px;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  padding: 8px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }

  .chat-section,
  .preview-section {
    flex: none;
    height: 50vh;
  }
}

@media (max-width: 768px) {
  .header-bar {
    padding: 12px 16px;
  }

  .app-name {
    font-size: 16px;
  }

  .main-content {
    padding: 8px;
    gap: 8px;
  }
}
</style>
